<template>
  <div class="check-sheets-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Memo /></el-icon>
          <div class="header-text">
            <h2>盘点单</h2>
            <p>记录商品盘点详细数据</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            新建盘点单
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 关联任务单信息 -->
    <el-card shadow="never" class="task-info-card" v-if="searchForm.taskNo">
      <el-alert
        :title="`关联任务单：${searchForm.taskNo}`"
        type="info"
        :closable="false"
      >
        <template #default>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span>正在查看该任务单下的所有盘点单，任务盈亏金额为下方所有盘点单的汇总</span>
            <el-button size="small" @click="handleClearTaskFilter">
              <el-icon><Close /></el-icon>
              清除筛选
            </el-button>
          </div>
        </template>
      </el-alert>
    </el-card>

    <!-- 筛选 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="盘点单号">
          <el-input v-model="searchForm.sheetNo" placeholder="请输入盘点单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="任务单号">
          <el-input v-model="searchForm.taskNo" placeholder="请输入任务单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchForm.warehouseId" placeholder="全部仓库" clearable style="width: 150px">
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable style="width: 150px">
            <el-option label="待盘点" value="pending" />
            <el-option label="盘点中" value="checking" />
            <el-option label="已完成" value="completed" />
            <el-option label="已审核" value="approved" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 盘点单列表 -->
    <el-card shadow="never">
      <el-table :data="filteredSheets" stripe border style="width: 100%">
        <el-table-column type="expand">
          <template #default="{ row }">
            <div style="padding: 20px;">
              <h4 style="margin-top: 0;">盘点明细</h4>
              <el-table :data="row.items" border size="small">
                <el-table-column prop="productCode" label="商品编码" width="150" />
                <el-table-column prop="productName" label="商品名称" min-width="200" />
                <el-table-column prop="bookQty" label="账面数量" width="120" align="right" />
                <el-table-column prop="actualQty" label="实盘数量" width="120" align="right">
                  <template #default="{ row: item }">
                    <span :class="{ 'diff-text': item.bookQty !== item.actualQty }">
                      {{ item.actualQty }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="diffQty" label="盈亏数量" width="120" align="right">
                  <template #default="{ row: item }">
                    <span :class="getDiffClass(item.diffQty)">
                      {{ item.diffQty > 0 ? '+' : '' }}{{ item.diffQty }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="单价" width="120" align="right">
                  <template #default="{ row: item }">
                    ¥{{ item.unitPrice.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="diffAmount" label="盈亏金额" width="150" align="right">
                  <template #default="{ row: item }">
                    <span :class="getDiffClass(item.diffAmount)">
                      {{ item.diffAmount > 0 ? '+' : '' }}¥{{ Math.abs(item.diffAmount).toFixed(2) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="150" />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sheetNo" label="盘点单号" width="180" fixed>
          <template #default="{ row }">
            <el-link type="primary" @click="handleViewSheet(row)">{{ row.sheetNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="taskNo" label="关联任务单" width="180" />
        <el-table-column prop="warehouseName" label="盘点仓库" width="120" />
        <el-table-column prop="totalItems" label="商品数量" width="100" align="right" />
        <el-table-column prop="totalDiffQty" label="盈亏总数" width="120" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.totalDiffQty)">
              {{ row.totalDiffQty > 0 ? '+' : '' }}{{ row.totalDiffQty }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="totalDiffAmount" label="盈亏总金额" width="150" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.totalDiffAmount)">
              {{ row.totalDiffAmount > 0 ? '+' : '' }}¥{{ Math.abs(row.totalDiffAmount).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkPerson" label="盘点人" width="100" />
        <el-table-column prop="checkTime" label="盘点时间" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewSheet(row)" size="small">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button link type="warning" @click="handleEditSheet(row)" size="small" v-if="row.status === 'pending'">
              <el-icon><Edit /></el-icon>
              录入
            </el-button>
            <el-button link type="success" @click="handleApproveSheet(row)" size="small" v-if="row.status === 'completed'">
              <el-icon><Select /></el-icon>
              审核
            </el-button>
            <el-button link type="danger" @click="handleDeleteSheet(row)" size="small" v-if="row.status === 'pending'">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新建盘点单对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建盘点单" width="600px" destroy-on-close>
      <el-form :model="sheetForm" :rules="sheetRules" ref="sheetFormRef" label-width="120px">
        <el-form-item label="关联任务单" prop="taskId">
          <el-select v-model="sheetForm.taskId" placeholder="选择任务单（选填）" style="width: 100%" clearable>
            <el-option
              v-for="task in availableTasks"
              :key="task.id"
              :label="`${task.taskNo} - ${task.taskName}`"
              :value="task.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点仓库" prop="warehouseId">
          <el-select v-model="sheetForm.warehouseId" placeholder="请选择仓库" style="width: 100%">
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点人" prop="checkPerson">
          <el-input v-model="sheetForm.checkPerson" placeholder="请输入盘点人" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="sheetForm.remark" type="textarea" :rows="3" placeholder="请输入备注（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveSheet">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Memo, Plus, Download, Search, Refresh, View, Edit, Select, Delete, Close
} from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 状态
const showCreateDialog = ref(false)
const sheetFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  sheetNo: '',
  taskNo: route.query.taskNo || '',
  taskId: route.query.taskId || null,
  warehouseId: null,
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 仓库数据
const warehouses = ref([
  { id: 1, name: '主仓库' },
  { id: 2, name: '分仓A' },
  { id: 3, name: '分仓B' }
])

// 可用任务
const availableTasks = ref([
  { id: 1, taskNo: 'CHK202401150001', taskName: '2024年1月全盘任务' },
  { id: 3, taskNo: 'CHK202401120003', taskName: '分仓A定期盘点' }
])

// 盘点单数据
const sheets = ref([
  {
    id: 1,
    sheetNo: 'CHS202401150001',
    taskNo: 'CHK202401150001',
    taskId: 1,
    warehouseId: 1,
    warehouseName: '主仓库',
    status: 'completed',
    checkPerson: '张三',
    checkTime: '2024-01-15 14:30:00',
    totalItems: 5,
    totalDiffQty: -15,
    totalDiffAmount: -4500,
    remark: '',
    createTime: '2024-01-15 08:30:00',
    items: [
      {
        productCode: 'P001',
        productName: 'iPhone 15 Pro Max 256GB',
        bookQty: 100,
        actualQty: 95,
        diffQty: -5,
        unitPrice: 9999,
        diffAmount: -49995,
        remark: '发现破损2台'
      },
      {
        productCode: 'P002',
        productName: 'MacBook Pro 14寸 M3',
        bookQty: 50,
        actualQty: 48,
        diffQty: -2,
        unitPrice: 14999,
        diffAmount: -29998,
        remark: ''
      },
      {
        productCode: 'P003',
        productName: 'AirPods Pro 2',
        bookQty: 200,
        actualQty: 205,
        diffQty: 5,
        unitPrice: 1899,
        diffAmount: 9495,
        remark: '发现未入库商品'
      }
    ]
  },
  {
    id: 2,
    sheetNo: 'CHS202401150002',
    taskNo: 'CHK202401150001',
    taskId: 1,
    warehouseId: 1,
    warehouseName: '主仓库',
    status: 'approved',
    checkPerson: '李四',
    checkTime: '2024-01-15 16:00:00',
    totalItems: 3,
    totalDiffQty: 8,
    totalDiffAmount: 2400,
    remark: '已审核通过',
    createTime: '2024-01-15 09:00:00',
    items: []
  }
])

// 盘点单表单
const sheetForm = reactive({
  taskId: null,
  warehouseId: null,
  checkPerson: '',
  remark: ''
})

// 表单验证规则
const sheetRules = {
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  checkPerson: [{ required: true, message: '请输入盘点人', trigger: 'blur' }]
}

// 计算属性
const filteredSheets = computed(() => {
  let result = sheets.value

  if (searchForm.sheetNo) {
    result = result.filter(sheet => sheet.sheetNo.includes(searchForm.sheetNo))
  }

  if (searchForm.taskNo) {
    result = result.filter(sheet => sheet.taskNo && sheet.taskNo.includes(searchForm.taskNo))
  }

  if (searchForm.warehouseId) {
    result = result.filter(sheet => sheet.warehouseId === searchForm.warehouseId)
  }

  if (searchForm.status) {
    result = result.filter(sheet => sheet.status === searchForm.status)
  }

  pagination.total = result.length
  return result
})

// 方法
const handleSearch = () => {
  pagination.page = 1
  ElMessage.success('搜索完成')
}

const handleReset = () => {
  Object.assign(searchForm, {
    sheetNo: '',
    taskNo: '',
    taskId: null,
    warehouseId: null,
    status: ''
  })
  handleSearch()
}

const handleClearTaskFilter = () => {
  searchForm.taskNo = ''
  searchForm.taskId = null
  handleSearch()
  router.push('/inventory/check-sheets')
}

const handlePageChange = () => {
  console.log('分页变化', pagination)
}

const handleViewSheet = (sheet) => {
  router.push(`/inventory/check-detail?id=${sheet.id}`)
}

const handleEditSheet = (sheet) => {
  router.push(`/inventory/check-input?id=${sheet.id}`)
}

const handleApproveSheet = (sheet) => {
  ElMessageBox.confirm('确定要审核通过该盘点单吗？', '提示', {
    type: 'warning'
  }).then(() => {
    sheet.status = 'approved'
    ElMessage.success('审核成功')
  }).catch(() => {})
}

const handleDeleteSheet = (sheet) => {
  ElMessageBox.confirm('确定要删除该盘点单吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = sheets.value.findIndex(s => s.id === sheet.id)
    if (index > -1) {
      sheets.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

const handleSaveSheet = () => {
  sheetFormRef.value.validate((valid) => {
    if (valid) {
      const warehouse = warehouses.value.find(w => w.id === sheetForm.warehouseId)
      const task = sheetForm.taskId ? availableTasks.value.find(t => t.id === sheetForm.taskId) : null
      
      const newSheet = {
        id: Date.now(),
        sheetNo: 'CHS' + new Date().getTime(),
        taskNo: task?.taskNo || '',
        taskId: sheetForm.taskId,
        warehouseId: sheetForm.warehouseId,
        warehouseName: warehouse.name,
        status: 'pending',
        checkPerson: sheetForm.checkPerson,
        checkTime: null,
        totalItems: 0,
        totalDiffQty: 0,
        totalDiffAmount: 0,
        remark: sheetForm.remark,
        createTime: new Date().toLocaleString(),
        items: []
      }
      
      sheets.value.unshift(newSheet)
      ElMessage.success('创建成功')
      showCreateDialog.value = false
      
      // 跳转到录入页面
      router.push(`/inventory/check-input?id=${newSheet.id}`)
    }
  })
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

// 工具函数
const getStatusName = (status) => {
  const map = {
    pending: '待盘点',
    checking: '盘点中',
    completed: '已完成',
    approved: '已审核'
  }
  return map[status] || status
}

const getStatusTagType = (status) => {
  const map = {
    pending: 'info',
    checking: 'warning',
    completed: '',
    approved: 'success'
  }
  return map[status] || ''
}

const getDiffClass = (value) => {
  if (value > 0) return 'profit-text'
  if (value < 0) return 'loss-text'
  return ''
}
</script>

<style scoped>
.check-sheets-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.task-info-card {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.diff-text {
  color: #E6A23C;
  font-weight: 500;
}

.profit-text {
  color: #67C23A;
  font-weight: 500;
}

.loss-text {
  color: #F56C6C;
  font-weight: 500;
}
</style>

